package com.huanzhidadi.java8inaction.chapter2;

import com.alibaba.fastjson2.JSON;
import com.huanzhidadi.java8inaction.model.Apple;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 通过给苹果列表排序的例子，来对Lambda和方法引用做一下演练
 */
@Slf4j
public class ComparatorTest {

    public static void main(String[] args) {
        List<Apple> inventory = Arrays.asList(
                new Apple(80, "green"),
                new Apple(155, "green"),
                new Apple(122, "red"));

        // 传递对象
        inventory.sort(new AppleComparator());
        log.info(JSON.toJSONString(inventory));

        // 使用匿名类
        inventory.sort(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o2.getWeight().compareTo(o1.getWeight());
            }
        });
        log.info(JSON.toJSONString(inventory));

        // 使用Lambda表达式
        inventory.sort((Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));
        log.info(JSON.toJSONString(inventory));

        // 使用方法引用
        inventory.sort(Comparator.comparing(Apple::getWeight).reversed());
        log.info(JSON.toJSONString(inventory));

    }
}
